package com.sjtu.rest;

import com.sjtu.constants.ApiConstants;
import com.sjtu.constants.TaskConstants;
import com.sjtu.dao.model.JobRunHistory;
import com.sjtu.dao.repository.JobRunHistoryRepository;
import com.sjtu.form.JobResult;
import com.sjtu.web.BaseRest;
import com.sjtu.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * nerine
 * 1/29/2020
 */
@Slf4j
@RestController
public class JobResultReceiveRest extends BaseRest {
    @Autowired
    private JobRunHistoryRepository jobRunHistoryRepository;

    @PostMapping(ApiConstants.SERVER_PUSH_BACK_URL)
    public Result<?> receive(@Valid @RequestBody JobResult jobResult) {
        log.info("job result receive, {}, {} ", jobResult.getSequenceId(), jobResult.isSuccess());
        JobRunHistory jobRunHistory = jobRunHistoryRepository.findById(jobResult.getSequenceId()).get();
        if(jobResult.isSuccess()) {
            jobRunHistory.setStatus(TaskConstants.TaskRunStatus.SUCCESS);
        }else {
            jobRunHistory.setStatus(TaskConstants.TaskRunStatus.FAIL);
            jobRunHistory.setRemark(jobResult.getFailMsg());
        }
        jobRunHistory.setRunBeginTime(jobResult.getBeginTime());
        jobRunHistory.setRunEndTime(jobResult.getEndTime());
        jobRunHistoryRepository.save(jobRunHistory);
        return success();
    }
}
